import 'dart:async';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/system_ui_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'building_index_module_list_response_bean.dart';
import 'building_index_module_view_model.dart';

/// ai海报首页
class BuildingIndexChangeModelPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BuildingIndexChangeModelPage";
  ///模板id
  final String moduleId;
  ///指示牌id
  final String buildingIndexId;
  const BuildingIndexChangeModelPage(
      {Key key, this.buildingIndexId, this.moduleId}) : super(key:key);

  @override
  _BuildingIndexChangeModelPageState createState() => _BuildingIndexChangeModelPageState();

  static Future<dynamic> navigatorPush(BuildContext context, String buildingIndexId, String moduleId){
    return RouterUtils.routeForFutureResult(
        context,
        BuildingIndexChangeModelPage(
          moduleId: moduleId,
          buildingIndexId: buildingIndexId,
        ),
        routeName: BuildingIndexChangeModelPage.ROUTER
    );
  }

}

class _BuildingIndexChangeModelPageState
    extends BasePagerState<BuildingIndexModuleBean, BuildingIndexChangeModelPage>
    with VgPlaceHolderStatusMixin{

  BuildingIndexModuleViewModel _viewModel;
  BuildingIndexViewModel _commonViewModel;

  String _selectModuleId;
  //用于标志是否是第一次将选中的模板放到第一位
  bool _firstRange = false;
  List<BuildingIndexModuleBean> _rangeList;
  @override
  void initState() {
    super.initState();
    _rangeList = new List();
    _selectModuleId = widget?.moduleId;
    _viewModel = BuildingIndexModuleViewModel(this);
    _commonViewModel = BuildingIndexViewModel(this);
    _viewModel?.refresh();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return  Column(
      children: [
        _toTopBarWidget(),
        SizedBox(height: 10,),
        Expanded(child: _toPlaceHolderWidget()),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "更换模板",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toConfirmWidget(),
    );
  }
  ///完成
  Widget _toConfirmWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        _commonViewModel.changeBuildingIndexModule(context, widget?.buildingIndexId, _selectModuleId);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Container(
          height: 24,
          width: 48,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              borderRadius: BorderRadius.circular(12)
          ),
          child: Text(
            "完成",
            style: TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w500
            ),
          ),
        ),
      ),

    );
  }


  ///列表页
  Widget _toPlaceHolderWidget(){
    return VgPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        loadingStatus: data == null,
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this,
            refreshBgColor: Colors.white,
            viewModel: _viewModel,
            child: _toGridPage())
    );
  }


  Widget _toGridPage(){
    if(data != null && data.isNotEmpty){
      if(_rangeList.isEmpty){
        List<BuildingIndexModuleBean> tempList = new List();
        tempList.addAll(data);
        int selectIndex = -1;
        for(int i = 0; i < tempList.length; i++){
          if(_selectModuleId == tempList[i].id){
            selectIndex = i;
          }
        }

        if(selectIndex != -1){
          _rangeList.add(tempList.removeAt(selectIndex));
          _rangeList.addAll(tempList);
        }
      }
    }
    return GridView.builder(
      padding: EdgeInsets.only(
          left: 15,
          right: 15,
          bottom: getNavHeightDistance(context)
      ),
      itemCount: _rangeList?.length ?? 0,
      physics: BouncingScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 6,
        crossAxisSpacing: 6,
        childAspectRatio: 113 / 193.1,
      ),
      itemBuilder: (BuildContext context, int index) {
        return _toGridItemWidget(context, _rangeList?.elementAt(index), index);
      },
    );
  }


  Widget _toGridItemWidget(BuildContext context, BuildingIndexModuleBean itemBean, int index) {
    String picUrl = "";
    String bigPicUrl = "";
    if(StringUtils.isNotEmpty(itemBean?.picurl)){
      picUrl = itemBean?.picurl;
      // bigPicUrl = itemBean.picurl + "?x-oss-process=style/style800";
      bigPicUrl = itemBean.picurl;
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        // BuildingIndexModelDetailPage.navigatorPush(context);
        if(_selectModuleId == itemBean.id){
          return;
        }
        _firstRange = true;
        setState(() {
          _selectModuleId = itemBean.id;
        });
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: BoxDecoration(
                  color: Colors.white
              ),
              child: VgCacheNetWorkImage(picUrl,
                fit: BoxFit.fill,
                imageQualityType: ImageQualityType.middleDown,),
            ),
            Align(
              alignment: Alignment.bottomLeft,
              child: Container(
                height: 24,
                alignment: Alignment.center,
                color: (itemBean.id == _selectModuleId)?ThemeRepository.getInstance().getPrimaryColor_1890FF():Colors.white.withOpacity(0.6),
                child: Image.asset(
                  "images/icon_select_model.png",
                  width: 13,
                ),
              ),
            ),
            Align(
              alignment: Alignment.topRight,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  VgPhotoPreview.single(context, bigPicUrl,
                      loadingCoverUrl: picUrl,
                      loadingImageQualityType: ImageQualityType.original,
                  photoPreviewType: PhotoPreviewType.image);
                },
                child: Padding(
                  padding: EdgeInsets.all(4),
                  child: Image.asset(
                    "images/icon_show_module_big_image.png",
                    width: 18,
                    height: 18,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
